import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueSetupExtend from 'vite-plugin-vue-setup-extend'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'
//散列值
const hash = Math.floor(Math.random() * 90000) + 10000

//模块分包 模块版本不变则每次生产的文件名一致
const chunksModulesMap:{[key:string]:Array<string>} = {
  vue:['vue', 'vue-router', 'vuex'],
  pdfmake:['pdfmake'],
  exceljs:['exceljs'],
  element:['element', 'ant-design'],
  echarts:['echarts'],
  mathjs:['mathjs'],
  vendor:['vendor']
}

//获取名称
const getName = (id:string, map:{[key:string]:Array<string>}) => {
  let name = ''
  for (const key in map) {
    const item = map[key]
    for (let i = 0, l = item.length; i < l; i++) {
      if (id.includes(item[i])) {
        name = key
        return name
      }
    }
    if (name) {
      break
    }
  }
  return name
}
//配置
export default defineConfig(({mode}) => {
  const useSuffix = mode === 'production' || mode === 'prepro'
  return {
    base:'/',
    resolve: {
      alias: [
        {
          find: '@',
          replacement: path.resolve(__dirname, 'src')
        }
      ],
      extensions: ['.js', '.ts', '.jsx', '.tsx', '.json', '.vue']
    },
    plugins: [
      vue(),
      vueSetupExtend(),
      // svgLoader()
      createSvgIconsPlugin({
        // 指定需要缓存的图标文件夹
        iconDirs:[path.resolve(process.cwd(), 'src/assets/icons')],
        // 指定symbolId格式
        symbolId:'icon-[dir]-[name]',
        inject:'body-first'
      })
    ],
    esbuild: {
      drop: useSuffix ? ['console', 'debugger'] : []
    },
    build: {
      minify: 'esbuild',
      rollupOptions: {
        output: {
          entryFileNames: 'assets/' + '[name]' + hash + '.js',
          chunkFileNames:(chunkInfo) => {
            if (chunksModulesMap[chunkInfo.name]) {
              return 'assets/[name]-[hash].js'
            } else {
              return 'assets/' + '[name]' + hash + '.js'
            }
          },
          assetFileNames: 'assets/' + '[name]' + hash + '.[ext]',
          manualChunks:(id, {getModuleInfo}) => {
            if (id.includes('node_modules')) {
              const name = getName(id, chunksModulesMap)
              return name ? name : 'vendor'
            }
            // else if (id.includes('src/')) {
            //   const info = getModuleInfo(id)
            //   if (info && info.importers.length + info.dynamicImporters.length > 1) {
            //     return 'manifest'
            //   }
            // }
          }
        }
      }
    },
    server:{
      port:1888,
      proxy:{
        // 选项写法
        '/api': {
          // 测试环境
          target: 'http://120.78.159.42:8080',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '')
        }
      }
    }
  }
})
